import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Notification } from 'element-ui';
import config from "@/config"
import tool from '@/utils/tool';
import dish from "./modules/dish";

Vue.use(Router)

const files = require.context('./modules', false, /\.js$/);
const modules = [];
files.keys().forEach((key) => {
	var items= files(key).default
   if(  items  instanceof Array){
	items.forEach(item=>{
		modules.push(item);
	});
   }else{
	modules.push(items);
   }

})


try {
	const originalPush = Router.prototype.push
	Router.prototype.push = function push(location) {
		return originalPush.call(this, location).catch(err => err)
	}
} catch (e) {
	console.info(e);
}

//系统特殊路由
const routes_404 = {
	path: "/:pathMatch(.*)*",
	hidden: true,
	component: () => import(/* webpackChunkName: "404" */ '@/views/other/404'),
}

export const mapMenu = [
	{
		path: '/',
		redirect: 'login'
	},
	{
		path: '/login',
		name: 'login',
		component: resolve => require(['@/views/login'], resolve),
	},
	{
		name: "layout",
		path: "/",
		component: () => import(/* webpackChunkName: "layout" */ '@/layout'),
		redirect: '/dashboard',
		children: [
			{
				name: "home",
				path: "/home",
				component: () => import(`@/views/home`),
				meta: {
					title: "首页",
					icon: "el-icon-platform-eleme"
				},
			},
			...modules
		]
	}
]

var router = new Router({
	routes: mapMenu
});

//判断是否已加载过API路由
var isGetApiRouter = false;

router.initMenu=function(){
	console.info("初始化菜单...");
		//isGetApiRouter = true;
	//加载API路由
	if (!isGetApiRouter) {
		let menu = tool.data.get("menu");
		menu = [{
			path: '/demo',
			name: 'demo',
			component: "demo",
		}];
		//menu=[];
		if (menu.length > 0) {
			var apiRouter = filterAsyncRouter(menu);
			apiRouter.forEach(item => {
				console.info(item);
				try {
					router.addRoute(item)
				} catch (error) {
					console.error(error);
				}
				//router.addRoute("home", item)

			})
			router.addRoute(routes_404)
		}

		isGetApiRouter = true;
	}
}
router.initMenu();


router.beforeEach((to, from, next) => {
	NProgress.start()
	console.info("to:" + to.path);
	console.info("from:" + from.path);
	//动态标题
	document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`
	let token = tool.data.get("sessionToken");
	if (to.path === "/login") {
		isGetApiRouter = false;
		next();
		return false;
	}
	if (!token) {
		next({
			path: '/login'
		});
		return false;
	}
	next();
});

router.afterEach(() => {
	NProgress.done()
});

router.onError((error) => {
	NProgress.done();
	Notification.error({
		title: '路由错误',
		message: error.message
	});
});

//转换
function filterAsyncRouter(routerMap) {
	const accessedRouters = []
	routerMap.forEach(item => {
		item.meta = item.meta ? item.meta : {};
		//处理外部链接特殊路由
		if (item.meta.type == 'iframe') {
			item.meta.url = item.path;
			item.path = `/i/${item.name}`;
		}
		//MAP转路由对象
		var route = {
			path: item.path,
			name: item.name,
			meta: item.meta,
			redirect: item.redirect,
			children: item.children ? filterAsyncRouter(item.children) : null,
			component: loadComponent(item.component)
		}
		accessedRouters.push(route)
	})
	return accessedRouters
}
function loadComponent(component) {
	if (component) {
		return () => import(/* webpackChunkName: "[request]" */ `@/views/${component}`)
	} else {
		return () => import(`@/views/other/empty`)
	}

}

export default router;